#coding=utf-8
'''
Created on 2010-10-12

@author: zarra
'''


from utils import quick_test_doctor
from model.expr_a import expr_a
from model.expr_a import Patient
from model.expr_a import Department
from model.expr_a import Ryjl,Bcjl,Bljy
from datetime import  date,datetime,time,timedelta
from utils import ExprActionManager
import conf


class Patient_Filter(object):
    
    def __init__(self):
        s=expr_a()
        self.filters=(
                      (u'在院病人' ,self._patient_filter_in_hospital),
                      (u'近期出院' , self._patient_filter_recent_cy),
                      (u'转出病人' , self._patient_filter_trans_department),
                      (u'其他病人' ,  self._patient_filter_others),
                      )
        _departments_all =  s.query(Department).filter(Department.is_del == 0).all()
        self.departments_all = {}
        for department in _departments_all:
            id=department.id.strip()
            self.departments_all[id]=department
        #print self.departments_all
        s.close()
    def _patient_filter_in_hospital(self,query,permissions):
        '''在院病人'''
        return query.filter(Patient.flag==u'在院')\
                    .filter(Patient.department.in_(permissions))
                    
    
    def _patient_filter_recent_cy(self,query,permissions):
        '''7天内出院病人'''
        days = timedelta(days = 7)
        today = datetime.combine(date.today(), time())
        prev_day = today -days
        str_prev_day = prev_day.strftime('%Y%m%d')
        return query.filter(Patient.flag==u'出院')\
                .filter(Patient.department.in_(permissions))\
                .filter(Patient.cy_time > str_prev_day) 
                
                
    def _patient_filter_trans_department(self,query,permissions):
        '''转科病人'''
        return query.filter(Patient.flag==u'在院')\
                .filter(Patient.begin_department.in_(permissions))\
                .filter(~Patient.department.in_(permissions))
                
    
    def _patient_filter_others(self,query,permissions):
        '''其他病人'''
        doctor = quick_test_doctor()
        today = datetime.today()
        s=expr_a()
        expr_ids = s.query(Bljy.expr_id)\
            .filter(Bljy.doctor_id == doctor.id)\
            .filter(Bljy.end_time > today).all()
            #.filter(Bljy.is_approval == '1')\
        if len(expr_ids)<1:
            return None
        ids = [id[0] for id in expr_ids]
        return query.filter(Patient.expr_id.in_(ids))
                   
    
    def _process_squery_patient(self,patients):
        '''处理病人列表,按病区归放'''
        department_wards={}
        ward_patients ={}
        for patient in patients:
            department_id = patient.department.strip()
            bq_id = patient.bq.strip()
            
            if not department_wards.has_key(department_id):
                department_wards[department_id]=set()
            department = department_wards[ department_id ]
            
            current_bq = self.departments_all[bq_id]
            department.add(  current_bq )
                
            if not ward_patients.has_key(department_id):
                ward_patients[department_id]={}
            if not  ward_patients[department_id].has_key(bq_id):
                ward_patients[department_id][bq_id]=[]
            bq = ward_patients[department_id][bq_id]
            
            bq.append(patient)
        departments=[]
        for department in department_wards.keys():
            department_object = self.departments_all[department]
            departments.append((department_object.id,department_object.name))
            wards = department_wards[department]
            list_wards =list()
            for ward in wards:
                list_wards.append((ward.id,ward.name))
            department_wards[department]=list_wards
            
        return departments,department_wards,ward_patients
    
    def avialable_department(self):
        doctor=quick_test_doctor()
        p=doctor.permissions
        return {'success':True,'data':p,'count':len(p)}
    
    def avialable_patients(self):
        s=expr_a()
        doctor=quick_test_doctor()
        
        permissions=[d.id for d in doctor.permissions]
        data={}
        types=[]
        for k,v in self.filters:
            query = s.query(Patient)
            query  = v(query, permissions)
            if query == None:
                continue
            patients = query.all()
            if len(patients) >0 :
                d1,d2,d3 = self._process_squery_patient(patients)
                types.append((k,))
                data[k]={
                         'departments':d1,
                         'wards':d2,
                         'patients':d3,
                         }     
        s.close()    
        return  {'success':True,'data':data,'types':types}
    def patient_info_by_id(self,id):
        s=expr_a()
        p=s.query(Patient).filter(Patient.zy_id == id ).first()
        return {'success':p!=None,'patient':p}
  
class Bl_Filter(object):
    def __init__(self):
        pass
    def avialable_bl(self,patient_id):
        pass
        
from drug import Drug_Filter
from right_tree import Tree,TreeNode  ,Drug_post_Tree      
class Direct(ExprActionManager):
    def __init__(self):
        super(Direct,self).__init__('/direct')
        self.register_action(Patient_Filter(), )       
        self.register_action(Drug_Filter(), ) 
        
        root = TreeNode('root','root');
        self.register_action(Drug_post_Tree(root),)
        
if __name__ == '__main__':
    import json
    def __json_default__(o):
        if isinstance(o, set):
            l=list(o)
            return json.dumps(l,default=__json_default__)
        try:
            getattr(o, '__json__')
            has_json =True
        except AttributeError:
            has_json=False
        if has_json :
            return o.__json__()
        else:
            print o
            raise TypeError('%r is not JSON serializable' % o)
    case = Patient_Filter()
    p=case.avialable_patients()
    print p['types'][0]
    result = json.dumps(p['types'],default=__json_default__)
    print result
    
 
    

